import winreg
import zipfile
from pathlib import Path

import chardet
from pandas import DataFrame
from pandas import read_csv, read_excel


def get_chrome_path(self):
    registry_paths = [
        (winreg.HKEY_CURRENT_USER, r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe'),
        (winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe'),
    ]

    for root, subkey in registry_paths:
        try:
            with winreg.OpenKey(root, subkey) as key:
                chrome_path, _ = winreg.QueryValueEx(key, None)
                return chrome_path
        except FileNotFoundError:
            continue
        except Exception as e:
            self.logger.warning(f"读取谷歌浏览器失败: {root}\\{subkey} -> {e}")
    return None

# 检测文件编码的函数
def detect_encoding(self, file):
    raw_data = file.read(10000)  # 读取文件的前10000个字节进行检测
    result = chardet.detect(raw_data)
    file.seek(0)  # 重置文件指针
    return result['encoding']

def read_csv_file(path: Path, detect_encoding_func) -> DataFrame:
    with open(path, 'rb') as f:
        encoding = detect_encoding_func(f)
    if '营销概况' in str(path):
        return read_csv(path, encoding=encoding, skiprows=1, nrows=4)
    return read_csv(path, encoding=encoding)

def read_excel_file(path: Path) -> DataFrame:
    df = read_excel(path, engine='openpyxl')
    return df.loc[:, ~df.columns.str.contains('同比')]

def read_zip_file(path: Path, detect_encoding_func) -> DataFrame:
    with zipfile.ZipFile(path, 'r') as z:
        for filename in z.namelist():
            with z.open(filename) as f:
                if filename.endswith('.csv'):
                    encoding = detect_encoding_func(f)
                    return read_csv(f, encoding=encoding)
                elif filename.endswith('.xlsx'):
                    return read_excel(f, engine='openpyxl')
    raise ValueError("压缩包中不包含支持的文件类型（csv/xlsx）")